package cn.seaboot.admin.security.jwt;

import cn.seaboot.commons.core.Converter;
import cn.seaboot.commons.core.UUIDUtils;
import cn.seaboot.commons.digest.AES;
import cn.seaboot.commons.digest.MD5;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.crypto.SecretKey;
import java.util.Date;

/**
 * 基于HS256算法实现
 *
 * @author Mr.css
 * @version 2022-01-05 15:03
 */
@Component
public class JwtHS256 implements AuthenticationJwt {

    private SecretKey secretKey;

    @Resource
    private SecurityJwtProperties securityJwtProperties;

    /**
     * 初始化密钥
     */
    @PostConstruct
    public void init() {
        String secretKey = securityJwtProperties.getSecretKey();
        this.secretKey = AES.genKey(MD5.hexBit32(secretKey).getBytes());
    }

    /**
     * 生成jwt
     *
     * @param authentication 登录凭证
     * @return jwt
     */
    @Override
    public String encrypt(Authentication authentication) {
        Date now = new Date();
        JwtBuilder builder = Jwts.builder();
        // 每一次都是唯一不可复制的
        builder.setId(UUIDUtils.genUUID22());
        // 主题，用户账号
        builder.setSubject(Converter.toString(authentication.getPrincipal()));
        //  签发时间
        builder.setIssuedAt(now);
        //  签名算法以及密匙
        builder.signWith(SignatureAlgorithm.HS256, secretKey);
        //  设置超时时间
        builder.setExpiration(new Date(now.getTime() + securityJwtProperties.getTimeoutMs()));
        return builder.compact();
    }

    /**
     * 解析JWT字符串
     *
     * @param jwt jwt
     * @return Claims
     */
    @Override
    public Claims decrypt(String jwt) {
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
    }
}












